<?php
// +----------------------------------------------------------------------
// | CoreThink [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.corethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: jry <598821125@qq.com> <http://www.corethink.cn>
// +----------------------------------------------------------------------
namespace Home\Controller;

use Think\Controller;
use Com\DingdingAuth;
/**
 * 后台用户控制器
 * 
 * @author jry <598821125@qq.com>
 */
class TaskController extends HomeController
{

	public function _initialize()
	{
		vendor('dingding.api.Auth');
		vendor('dingding.api.User');
	}
	/**
	 * 钉钉
	 * 获取用户信息
	 */
	public function get_userinfo()
	{
	
// 		$Auth=new \Auth();
// 		$User=new \User();
// 		$accessToken = $Auth->getAccessToken();
		$code = I("code");
		//$userInfo = $User->getUserInfo($accessToken, $code);
		//Log::i("[USERINFO]".json_encode($userInfo));
		//$user=json_decode($userInfo,true);
		$corpid=C('CORPID');
		$corpsecret=C('SECRET');
		$D=new DingdingAuth($corpid, $corpsecret);
		$token = $D->getAccessToken();
			$param1=array(
    				'code'=>$code
    		);
    		$userInfo=$D->getDingRe("user/getuserinfo",'','GET',$param1);
		    		
    		$param=array(
    				'userid'=>$userInfo['userid'],
    		);
    		$user_all=$D->getDingRe("user/get",'','GET',$param);
    		
    		session('DING_USER',$user_all);
		
		echo json_encode($userInfo,true);
		
	}
	/**
	 * loading页面
	 */
    public function index()
    {
    	    	
    	$this->assign('meta_title', 'loading...');
    	$this->display();
		
    }
    /**
     * 首页
     */
    public function shouye()
    {
    	$user_info=session('DING_USER');
    	if (!$user_info) {
    		header('Location: '.U('Home/Task/index'));
    	}
    	$ding_id=$user_info['userid'];
    	$uid=M('Employee')->where(array('ding_id'=>$ding_id))->getField('id');
    	 
    	//最新任务
    	$where['uid'] =array('like', '%,' . $uid . ',%');
    	$where['creater'] =$uid;
    	$where['_logic']='or';
    	$map['_complex']=$where;
    	
    	$task_list = M('Task')->where($map)->limit(5)->order('create_time desc')->select();
    	foreach ($task_list as $k=>$v){
    		$task_list[$k]['projectid']=M('Project')->where('id='.$v['projectid'])->getField('project_number');
    		$uid_arr=explode(',',$v['uid']);
    		$uid_str=array();
    		foreach ($uid_arr as $kk=>$vv){
    			if ($vv!='') {
    				$employee_name = M('Employee')->field('name')->find($vv); // 员工姓名
    				$uid_str[$kk] = $employee_name['name'];
    			}
    		}
    		$task_list[$k]['uid']=implode("|",$uid_str);
    		//$user = get_user_info($v['creater']);
    		$task_list[$k]['creater']=M('Employee')->where(array('id'=>$v['creater']))->getField('name');
    	
    	}
    	
    	$this->assign('task_list', $task_list);
    	$this->assign('user_info', $user_info);
    	$this->assign('meta_title', '首页');
    	$this->display();
    }
   /**
     * 任务列表
     */
    public function mytask()
    {
    	$user_info=session('DING_USER');
    	if (!$user_info) {
    		header('Location: '.U('Home/Task/index'));
    	}
    	//dump($user_info);exit;
    	$ding_id=$user_info['userid'];
    	$uid=M('Employee')->where(array('ding_id'=>$ding_id))->getField('id');
    	
    	$where['uid'] =array('like', '%,' . $uid . ',%');
    	$where['creater'] =$uid;
    	$where['_logic']='or';
    	$map['_complex']=$where;
    	$status=I('status')?:2;
    	$map['status']=$status;
    	$map['pid']=0;
    	
    	$task_list = M('Task')->page(! empty($_GET["p"]) ? $_GET["p"] : 1, 8)->where($map)->order('emergency_level asc,id desc')->select();
    	$page = new \Common\Util\Page(M('Task')->where($map)->count(), 8);
    	foreach ($task_list as $k=>$v){
    		$task_list[$k]['projectid']=M('Project')->where('id='.$v['projectid'])->getField('project_number');
    		$uid_arr=explode(',',$v['uid']);
    		$uid_str=array();
    		foreach ($uid_arr as $kk=>$vv){
    			
    			if ($vv!='') {
    				$employee_name = M('Employee')->field('name')->find($vv); // 员工姓名
    				$uid_str[$kk]= $employee_name['name'];
    		    }
    		}
    		$task_list[$k]['uid']=implode("|",$uid_str);
    		//$task_list2[$k]['uid']=M('Employee')->where('id='.$v['uid'])->getField('name');
    		$task_list[$k]['emergency_level'] = M('Descriptions')->where(array('tablename'=>'emergency_level','fieldvalue'=>$v['emergency_level']))->getField('title');
    		$task_list[$k]['type'] = M('Descriptions')->where(array('tablename'=>'task_type','fieldvalue'=>$v['type']))->getField('title');
    		//$user = get_user_info($v['creater']);
    		$task_list[$k]['creater']=M('Employee')->where(array('id'=>$v['creater']))->getField('name');
    	
    		$task_list[$k]['start_time']?$task_list[$k]['start_time']=date('Y-m-d H:i:s',$v['start_time']):'';
    		$task_list[$k]['end_time']?$task_list[$k]['end_time']=date('Y-m-d H:i:s',$v['end_time']):'';
    		//$task_list[$k]['content']=mb_substr($v['content'],0,5,'utf-8').'....';
    	}
    	
    	$this->assign('status',$status);
    	$this->assign('meta_title', '我的任务');
    	$this->assign('task_list', $task_list);
    	$this->assign('page', $page->show());
    	$this->assign('user_info', $user_info);
    	$this->display();
    }
    /**
     * 开始任务
     */
    public function starTask(){
    	$id=I('id');
    	$data=array(
    			'status'=>1,
    			'start_time'=>time()
    			
    	);
    	$task= M('Task')->where('id='.$id)->save($data);
    	
    	$pid=I('pid');
    	if (!empty($pid)) {
    		$this->success('您的任务已经开始！',U('sontask',array('pid'=>$pid)));
    	}else{
    		$this->success('您的任务已经开始！',U('mytask',array('status'=>1)));
    	}

    }
    /**
     * 完结任务
     */
    public function finishTask(){
    	$id=I('id');
    	$data=array(
    			'status'=>3,
    			'end_time'=>time()
    			 
    	);
    	$task= M('Task')->where('id='.$id)->save($data);
    	 
    	$pid=I('pid');
    	if (!empty($pid)) {
    		$this->success('您的任务已经完结！',U('sontask',array('pid'=>$pid)));
    	}else{
    		$this->success('您的任务已经完结！',U('mytask',array('status'=>3)));
    	}
    	
    }
    /**
     * 动态
     */
    public function dongtai(){
    	$user_info=session('DING_USER');
    	if (!$user_info) {
    		header('Location: '.U('Home/Task/index'));
    	}
    	$ding_id=$user_info['userid'];
    	$uid=M('Employee')->where(array('ding_id'=>$ding_id))->getField('id');
    	
    	//最新任务
    	$where['uid'] =array('like', '%,' . $uid . ',%');
    	$where['creater'] =$uid;
    	$where['_logic']='or';
    	$map['_complex']=$where;
    	
    	$task_list = M('Task')->where($map)->limit(5)->order('create_time desc')->select();
    	foreach ($task_list as $k=>$v){
    		$task_list[$k]['projectid']=M('Project')->where('id='.$v['projectid'])->getField('project_number');
    		$uid_arr=explode(',',$v['uid']);
    		$uid_str=array();
    		foreach ($uid_arr as $kk=>$vv){
    			if ($vv!='') {
    				$employee_name = M('Employee')->field('name')->find($vv); // 员工姓名
    				$uid_str[$kk] = $employee_name['name'];
    			}
    		}
    		$task_list[$k]['uid']=implode("|",$uid_str);
    		//$user = get_user_info($v['creater']);
    		$task_list[$k]['creater']=M('Employee')->where(array('id'=>$v['creater']))->getField('name');
    		    		
    	}
    	
    	$star_count=M('Task')->where(array('uid'=>array('like', '%,' . $uid . ',%'),'status'=>array('eq',2)))->count();
    	$in_count=M('Task')->where(array('uid'=>array('like', '%,' . $uid . ',%'),'status'=>array('eq',1)))->count();
    	$end_count=M('Task')->where(array('uid'=>array('like', '%,' . $uid . ',%'),'status'=>array('eq',3)))->count();
    	
    	$this->assign('star_count', $star_count);
    	$this->assign('in_count', $in_count);
    	$this->assign('end_count', $end_count);
    	$this->assign('task_list', $task_list);
    	$this->assign('meta_title', '首页');
    	$this->assign('user_info', $user_info);
    	$this->display();
    }
    /**
     * 新增任务
     */
    public function addnew(){
    	$user_info=session('DING_USER');
    	if (!$user_info) {
    		header('Location: '.U('Home/Task/index'));
    	}
    	$corpid=C('CORPID');
    	$corpsecret=C('SECRET');
    	$D=new DingdingAuth($corpid, $corpsecret);
    	$token = $D->getAccessToken();
    	
    	if (IS_POST) {
    		
    		$project_object = D('Task');
    		$data = $project_object->create();
    		for ( $i = 1; $i <= 5; $i++)
    		{
    			if ($_POST["uid".$i.""]) {
    				$touser .=$_POST["uid".$i.""]."|";
    				$name=M('Employee')->where(array('ding_id'=>$_POST["uid".$i.""]))->getField('name');
    				$user_name .= $name."|";
    				$uid=M('Employee')->where(array('ding_id'=>$_POST["uid".$i.""]))->getField('id');
    				$uid_str .=",".$uid;
    			}
    			
    		}
    		$uid_str=$uid_str.",";
    		$data['uid']=$uid_str;
    		$data['status'] = 2;
    		$data['pid'] = 0;
    		$data['creater']=M('Employee')->where(array('ding_id'=>$_POST["creater"]))->getField('id');
    		//dump($data);exit;
    		$n=$project_object->add($data);
    		
    		//发钉钉消息需要的参数
    		$user_name=substr($user_name,0,-1);
    		$touser=substr($touser,0,-1);
    		$project_number=M('Project')->where('id='.$_POST['projectid'])->getField('project_number');
    		
    		$emergency_level = M('Descriptions')->where(array('tablename'=>'emergency_level','fieldvalue'=>$_POST['emergency_level']))->getField('title');
    		$type= M('Descriptions')->where(array('tablename'=>'task_type','fieldvalue'=>$_POST['type']))->getField('title');
    		
    		$content=$_POST['content'];
    		$creater=M('Employee')->where(array('ding_id'=>$_POST["creater"]))->getField('name');;
    		if ($n) {
    			//发钉钉消息
    			$message_url="http://".$_SERVER['HTTP_HOST']."/Wap/Task/mytask";
    			$data=array(
    					'touser'=>"$touser",
    					'agentid'=>C('AGENTID'),
    					'msgtype'=>'oa',
    					'oa'=>array(
    							'message_url'=>$message_url,
    							'head'=>array(
    									"bgcolor"=>"FFFF4234",
    									"text"=>"好聚点科技"
    							),
    							'body'=>array(
    									"title"=>"项目：".$project_number,
    									"form"=>array (
    											array(
    													"key"=> "执行人：",
    													"value"=>$user_name
    											),
    											array(
    													"key"=> "类型：",
    													"value"=>$type
    											),
    											array(
    													"key"=> "级别：",
    													"value"=>$emergency_level
    											),
    									),
    									"content"=>$content,
    									//"image"=>"@lADOADmaWMzazQKA",
    									//"file_count"=> "",
    									"author"=>$creater
    							),
    					),
    			);
    			 
    			$re=$D->getDingRe("message/send",$data,'POST','');
    			 
    			$this->success('新增任务成功', U('Home/Task/mytask'));
    		} else {
    			$this->error('新增失败');
    		}
    		
    		
    	}else{
    		
   		
    		$project_number=M('Project')->field('id,project_number as title')->select();
    		$task_type = D('Descriptions')->where('tablename="task_type"')
    		->field('fieldvalue as id,title')
    		->select();
    		$emergency_level = D('Descriptions')->where('tablename="emergency_level"')
    		->field('fieldvalue as id,title')
    		->select();
    		
    		$this->assign('project_number', $project_number);
    		$this->assign('task_type', $task_type);
    		$this->assign('emergency_level', $emergency_level);
    		$this->assign('meta_title', '新增任务');
    		$this->assign('user_info', $user_info);
    		$this->display();
    	}
    	
    }
    
    /**
     * 新增子任务
     */
    public function addson(){
    	$user_info=session('DING_USER');
    	if (!$user_info) {
    		header('Location: '.U('Home/Task/index'));
    	}
    	$corpid=C('CORPID');
    	$corpsecret=C('SECRET');
    	$D=new DingdingAuth($corpid, $corpsecret);
    	$token = $D->getAccessToken();
    	 
    	if (IS_POST) {
    
    		$project_object = D('Task');
    		$data = $project_object->create();
    		for ( $i = 1; $i <= 5; $i++)
    		{
    		if ($_POST["uid".$i.""]) {
    		$touser .=$_POST["uid".$i.""]."|";
    				$name=M('Employee')->where(array('ding_id'=>$_POST["uid".$i.""]))->getField('name');
    				$user_name .= $name."|";
    				$uid=M('Employee')->where(array('ding_id'=>$_POST["uid".$i.""]))->getField('id');
    						$uid_str .=",".$uid;
    		}
    		 
    		}
    		$uid_str=$uid_str.",";
    		$data['uid']=$uid_str;
    		$data['status'] = 2;
    		$data['creater']=M('Employee')->where(array('ding_id'=>$_POST["creater"]))->getField('id');
    		$data['pid']=I('p_id');
    		//dump($data);exit;
    				$n=$project_object->add($data);
    
    		//发钉钉消息需要的参数
    		$user_name=substr($user_name,0,-1);
    		$touser=substr($touser,0,-1);
    		$project_number=M('Project')->where('id='.$_POST['projectid'])->getField('project_number');
    
    		$emergency_level = M('Descriptions')->where(array('tablename'=>'emergency_level','fieldvalue'=>$_POST['emergency_level']))->getField('title');
    		$type= M('Descriptions')->where(array('tablename'=>'task_type','fieldvalue'=>$_POST['type']))->getField('title');
    
    				$content=$_POST['content'];
    				$creater=M('Employee')->where(array('ding_id'=>$_POST["creater"]))->getField('name');;
    				if ($n) {
    				//发钉钉消息
    					$message_url="http://".$_SERVER['HTTP_HOST']."/Wap/Task/mytask";
    				$data=array(
    						'touser'=>"$touser",
    						'agentid'=>C('AGENTID'),
    						'msgtype'=>'oa',
    							'oa'=>array(
    							'message_url'=>$message_url,
    									'head'=>array(
    											"bgcolor"=>"FFFF4234",
    											"text"=>"好聚点科技"
    							),
    							'body'=>array(
    													"title"=>"项目：".$project_number,
    													"form"=>array (
    													array(
    															"key"=> "执行人：",
    																	"value"=>$user_name
    																			),
    																			array(
    																			"key"=> "类型：",
    																			"value"=>$type
    																			),
    																			array(
    																			"key"=> "级别：",
    																			"value"=>$emergency_level
    																			),
    				),
    				"content"=>$content,
    				//"image"=>"@lADOADmaWMzazQKA",
    				//"file_count"=> "",
    				"author"=>$creater
    				),
    				),
    				);
    
    				$re=$D->getDingRe("message/send",$data,'POST','');
    
    				$this->success('新增子任务成功', U('Home/Task/sontask',array('pid'=>I('p_id'))));
    						} else {
    						$this->error('新增失败');
    						}
    
    		}else{
    
    				$pid=I('pid');	
    				$projectid =M('Task')->where(array('id'=>$pid))->getField('projectid');
    				
    				$project_number=M('Project')->field('id,project_number as title')->select();
    				$task_type = D('Descriptions')->where('tablename="task_type"')
    				->field('fieldvalue as id,title')
    				->select();
    				$emergency_level = D('Descriptions')->where('tablename="emergency_level"')
    				->field('fieldvalue as id,title')
    				->select();
    
    				$this->assign('pid', $pid);
    				$this->assign('projectid', $projectid);
    						$this->assign('project_number', $project_number);
    						$this->assign('task_type', $task_type);
    						$this->assign('emergency_level', $emergency_level);
    						$this->assign('meta_title', '新增子任务');
    						$this->assign('user_info', $user_info);
    						$this->display();
    		}
    							 
    }
    
    
    /**
     * 搜索项目
     */
     public function getProjectAjax(){
     	
     	$project_keyword = I('keyword');
		if(!empty($project_keyword)){
			$condition = array('like','%'.$project_keyword.'%');
			$map['id|project_name|project_number'] = array($condition,$condition,$condition,'_multi'=>true);
		}
		
		$list=M('Project')->where($map)->order("create_time desc")->select();
		foreach ($list as $k => $vo) {
	
				$data .= "<option value ='" . $vo['id'] . "'>" . $vo['project_number']."</option>";
			
		}
		$this->ajaxReturn($data);
     }
     
          
    /**
     * 子任务
     */
    public function sontask(){
    	$user_info=session('DING_USER');
    	if (!$user_info) {
    		header('Location: '.U('Home/Task/index'));
    	}
    	$ding_id=$user_info['userid'];
    	$uid=M('Employee')->where(array('ding_id'=>$ding_id))->getField('id');
    	 $pid=I('pid');
    	//子任务
    	 $where['uid'] =array('like', '%,' . $uid . ',%');
    	 $where['creater'] =$uid;
    	 $where['_logic']='or';
    	 $map['_complex']=$where;
    	$map['pid']=$pid;
    	
    	$task_list = M('Task')->where($map)->limit(5)->order('create_time desc')->select();
    	foreach ($task_list as $k=>$v){
    		$task_list[$k]['projectid']=M('Project')->where('id='.$v['projectid'])->getField('project_number');
    		$uid_arr=explode(',',$v['uid']);
    		$uid_str=array();
    		foreach ($uid_arr as $kk=>$vv){
    			if ($vv!='') {
    				$employee_name = M('Employee')->field('name')->find($vv); // 员工姓名
    				$uid_str[$kk] = $employee_name['name'];
    			}
    		}
    		$task_list[$k]['uid']=implode("|",$uid_str);
    		//$user = get_user_info($v['creater']);
    		$task_list[$k]['creater']=M('Employee')->where(array('id'=>$v['creater']))->getField('name');
    	
    	}
    	
    	$this->assign('pid', $pid);
    	$this->assign('task_list', $task_list);
    	$this->assign('meta_title', '子任务');
    	$this->assign('user_info', $user_info);
    	$this->display();
    }
    
    
}   
